<template>
  <h2>计算属性和监视</h2>
  <fieldset>
    <legend>姓名操作</legend>
    姓名:<input type="text" placeholder="请输入姓名" v-model="firstName" />
    <br />
    姓氏:<input type="text" placeholder="请输入姓氏" v-model="lastName" />
  </fieldset>
  <fieldset>
    <legend>计算属性和监视的演示</legend>
    姓名:<input type="text" placeholder="显示姓名" v-model="fullName" />
    <br />
    姓名:<input type="text" placeholder="显示姓名" :value="fullName1" />
    <br />
    姓名:<input type="text" placeholder="显示姓名" v-model="fullName2" />
    <br />
  </fieldset>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  reactive,
  toRefs,
  watch,
  ref,
  watchEffect
} from 'vue'

export default defineComponent({
  setup() {
    // 定义一个响应式的对象
    const userName = reactive({
      firstName: '',
      lastName: ''
    })
    // 通过计算属性的方式，实现第一个姓名的显示
    // 计算属性如果只传入一个回调函数，表示的是get
    // const fullName = computed(() => {
    //   return userName.firstName + '_' + userName.lastName
    // })
    const fullName = computed({
      get() {
        // 返回的是一个ref类型的对象
        return userName.firstName + '_' + userName.lastName
      },
      set(value: any) {
        console.log(value)
        const valueArr = value.split('_')
        userName.firstName = valueArr[0]
        userName.lastName = valueArr[1]
      }
    })
    let fullName1: any = ref('')
    // 当我们使用watch监视非响应式的数据的时候，需要使用回调的形式
    watch(
      [() => userName.firstName, () => userName.lastName],
      (newValue, oldValue) => {
        fullName1.value = newValue[0] + '_' + newValue[1]
      },
      { immediate: true }
    )
    watch(userName, () => {
      console.log(userName)
    })
    let fullName2: any = ref('')
    // 不需要配置immediate,本身默认就会进行监视(默认执行一次)
    watchEffect(() => {
      fullName2.value = userName.firstName + '_' + userName.lastName
    })
    return {
      ...toRefs(userName),
      fullName,
      fullName1,
      fullName2
    }
  }
})
</script>

<style scoped>
</style>W